<?php

class BasketbalFunctions
{

public $username;
public $user_key;

public function __construct()
    {
    	$this->username = $_SESSION['username'];
    	$this->user_key = $_SESSION['user_key'];
    }

public function FetchResults($sql)
	{
		require __DIR__ . '/../db_bb_connect.php';

		if ($db->query($sql)) {  

			$result = $db->query($sql);
	  		$row = $result->fetch_assoc();
	  		return $row;

	    	} else {
	      		echo "Error: " . $sql . "<br>" . $db->error;
	    	}   
	}

public function GetUserkeyFromUsername($username)
	{
		require __DIR__ . '/../db_bb_connect.php';

		$sql = "SELECT user_key FROM users WHERE username = '$username'";

		if ($db->query($sql)) { 
			$result = $db->query($sql);
  			$row = $result->fetch_assoc();
  			$user_key = $row['user_key'];
  			return $user_key;

   		} else {
     		$error = "Error: " . $sql . "<br>" . $db->error;
     		return $error;
    	}
	}

public function GetUserFirstnameFromUserkey($user_key)
	{
		require __DIR__ . '/../db_bb_connect.php';

		$sql = "SELECT firstname FROM users WHERE user_key = '$user_key'";

		if ($db->query($sql)) { 
			$result = $db->query($sql);
  			$row = $result->fetch_assoc();
  			$firstname = $row['firstname'];
  			return $firstname;

   		} else {
     		$error = "Error: " . $sql . "<br>" . $db->error;
     		return $error;
    	}
	}

public function GetUserLastnameFromUserkey($user_key)
	{
		require __DIR__ . '/../db_bb_connect.php';

		$sql = "SELECT lastname FROM users WHERE user_key = '$user_key'";

		if ($db->query($sql)) { 
			$result = $db->query($sql);
  			$row = $result->fetch_assoc();
  			$lastname = $row['lastname'];
  			return $lastname;

   		} else {
     		$error = "Error: " . $sql . "<br>" . $db->error;
     		return $error;
    	}
	}

public function GetActionTagNameFromActionTagID($tag_ID)
	{
		require __DIR__ . '/../db_bb_connect.php';

		$sql = "SELECT tag FROM video_feedback_taglist WHERE ID = '$tag_ID'";

		if ($db->query($sql)) { 
			$result = $db->query($sql);
  			$row = $result->fetch_assoc();
  			$tagname = $row['tag'];
  			return $tagname;

   		} else {
     		$error = "Error: " . $sql . "<br>" . $db->error;
     		return $error;
    	}
	}

public function GetGameEmbedCode($season, $gamenumber)
	{
		$sql = "SELECT embed_code 
		FROM games 
		WHERE season = '$season'
		AND gamenumber = '$gamenumber'";

		$row = $this->FetchResults($sql);

		$embed_code = $row['embed_code'];
		return $embed_code;
	}

public function LastGameStatsPlayer($playerid)
	{		
		$sql = "SELECT DISTINCT season 
		FROM teams 
		WHERE playerID = '$playerid'
		ORDER BY season DESC
		LIMIT 1";

		$row = $this->FetchResults($sql);
		$season =  $row['season'];

		$sql = "SELECT * 
		FROM stats 
		WHERE playerID = '$playerid' 
		AND DNP = 'no'
		ORDER BY season DESC, gamenumber DESC
		LIMIT 1 ";

		$row = $this->FetchResults($sql);

	    $DRB = $row['DRB']; 
		$ORB = $row['ORB']; 
		$TOV = $row['TOV']; 
		$ST = $row['ST']; 
		$AST = $row['AST']; 
		$BS = $row['BS']; 
		$FTscored = $row['FTscored']; 
		$FTtotal = $row['FTtotal']; 
		$FGscored = $row['FGscored']; 
		$FGtotal = $row['FGtotal'];
		$FGOscored = $row['FG_outside_scored'];
		$FGOtotal = $row['FG_outside_total'];
		$THPscored = $row['THPscored'];
		$THPtotal = $row['THPtotal'];
  		$PF = $row['PF']; 
  		$gamenumber = $row['gamenumber'];
  		$S5 = $row['S5'];

  		$minutesplayed = floor((int)$row['MP'] / 60);
  		$seconds = (int)$row['MP'] % 60;

  		if ( $seconds >= 0 && $seconds < 10) {
			$secondsplayed = "0$seconds";
		} else {
			$secondsplayed = $seconds;
		}

  		$MP = "$minutesplayed:$secondsplayed"; 

  		$sql="SELECT date, opponent, location, score_exc_tot,score_opp_tot
		  FROM games
		  WHERE season = '$season'
		  AND gamenumber = '$gamenumber'";

		$row = $this->FetchResults($sql);

		$date = $row['date'];
		$opponent = $row['opponent'];
		$location = $row['location'];
		$score_exc_tot = $row['score_exc_tot'];
		$score_opp_tot = $row['score_opp_tot'];

		?>

		<div class="row">
				<div class="col-md-12">
					<div class="table-responsive">
					<h4>Last Game - 
						<?php 
							if ( empty($row) ) {
								echo "<i>no game entered yet</i>";
							} else {
								echo "$opponent $location: $score_exc_tot-$score_opp_tot on $date";
							}
						?>
						</h4>
						<table class="table table-hover table-striped">
					    <thead>
					      <tr>
					        <th>DRB</th>
					        <th>ORB</th>
					        <th>TO</th>
					        <th>ST</th>
			 <?php if ($season >= '2018/2019') { 
			 	echo "<th>AST</th>";
			 	echo "<th>BS</th>";
			 	 } ?>					        
					        
		<?php if ($season < '2017/2018') {
		  echo "<th>FG</th>";
		} else if ($season >= '2017/2018') {
		  echo "<th>FGI</th>";
		  echo "<th>FGO</th>";
		  echo "<th>3P</th>";
		} 


		?>					<th>FT</th>
					        <th>PTS</th>
					        <th>PF</th>
					        <?php if ($season >= '2018/2019') { 
					        	echo "<th>MP</th>"; 
					        	echo "<th>S5</th>"; 

					        } ?>
					    </tr>
					    </thead>
					    <tbody>

				<?php if( empty($row) ){ 

					echo "<td colspan='14'> </td>"; 

				} else { ?>

					    	<td><?= $DRB; ?></td>
					    	<td><?= $ORB; ?></td>
					    	<td><?= $TOV; ?></td>
					    	<td><?= $ST; ?></td>
		<?php if ($season >= '2018/2019') { echo "<td>$AST</td>"; echo "<td>$BS</td>"; } ?>
					    
					    	
					    	
					    	<?php 
					    	if ($season < '2017/2018') {
					    		echo "<td>$FGscored/$FGtotal";
					    		if($FGtotal > 0) { echo "(" . round(($FGscored/$FGtotal)*100) . "%)";} 
								echo "</td>";

		} else if ($season >= '2017/2018') {
						    		echo "<td>$FGscored/$FGtotal";
					    		if($FGtotal > 0) { echo "(" . round(($FGscored/$FGtotal)*100) . "%)";} 
								echo "</td>";
											    		echo "<td>$FGOscored/$FGOtotal";
					    		if($FGOtotal > 0) { echo "(" . round(($FGOscored/$FGOtotal)*100) . "%)";} 
								echo "</td>";
											    		echo "<td>$THPscored/$THPtotal";
					    		if($THPtotal > 0) { echo "(" . round(($THPscored/$THPtotal)*100) . "%)";} 
								echo "</td>";

								}

		?>
		<td><?= $FTscored; ?>/<?= $FTtotal; ?><?php if($FTtotal > 0) { echo "(" . round(($FTscored/$FTtotal)*100) . "%)";} ?> </td>

					    	<td>
		<?php if ($season < '2017/2018') {
		  echo 2 * $FGscored + $FTscored;
		} else if ($season >= '2017/2018') {
		  echo 2 * $FGscored + 2 * $FGOscored + $FTscored + 3 * $THPscored;

		}
		?>
					    	</td>

					    	<td><?= $PF; ?></td>

					    	<?php if ($season >= '2018/2019') { 
					        	echo "<td>$MP</td>"; 
					        	echo "<td>$S5</td>"; 

					        } } ?>
					    </tbody>
					  </table>
					</div>
			</div>
		</div>


		<?php
	}

public function SeasonGameStatsPlayer($playerid)
	{
		//require __DIR__ . '/../db_bb_connect.php';
		$sql = "SELECT DISTINCT season 
		FROM teams 
		WHERE playerID = '$playerid'
		ORDER BY season DESC
		LIMIT 1";

		$row = $this->FetchResults($sql);
		$season =  $row['season'];

		$sql = "SELECT SUM(DRB) AS SUMDRB,  SUM(ORB) AS SUMORB, SUM(TOV) AS SUMTOV, SUM(ST) AS SUMST, SUM(AST) AS SUMAST,SUM(BS) AS SUMBS, SUM(FTscored) AS SUMFTscored, SUM(FTtotal) AS SUMFTtotal, SUM(FGscored) AS SUMFGscored, SUM(FGtotal) AS SUMFGtotal, SUM(FG_outside_scored) AS SUMFGOscored, SUM(FG_outside_total) AS SUMFGOtotal, SUM(THPscored) AS SUMTHPscored, SUM(THPtotal) AS SUMTHPtotal, SUM(PF) AS SUMPF, SUM(MP) AS SUMMP,(SELECT COUNT(*) FROM stats WHERE S5 = 'yes' AND playerID = '$playerid' AND season = '$season' ) AS SUMS5, 
		(SELECT COUNT(*) FROM stats WHERE DNP != 'no' AND playerID = '$playerid' AND season = '$season' ) AS DNPtot, 
		(SELECT COUNT(*) FROM stats WHERE DNP = 'yes' AND playerID = '$playerid' AND season = '$season' ) AS DNPgen, 
		(SELECT COUNT(*) FROM stats WHERE DNP = 'coach' AND playerID = '$playerid' AND season = '$season' ) AS DNPcoach, 
		(SELECT COUNT(*) FROM stats WHERE DNP = 'injury' AND playerID = '$playerid' AND season = '$season' ) AS DNPinjury, 
		COUNT(*) AS TOTALGAMES
		FROM stats 
		WHERE playerID = '$playerid' 
		AND season = '$season'";

		$row = $this->FetchResults($sql);

		$SUMDRB = $row['SUMDRB']; 
		$SUMORB = $row['SUMORB']; 
		$SUMTOV = $row['SUMTOV']; 
		$SUMST = $row['SUMST']; 
		$SUMAST = $row['SUMAST'];
		$SUMBS = $row['SUMBS'];
		$SUMFTscored = $row['SUMFTscored']; 
		$SUMFTtotal = $row['SUMFTtotal']; 
		$SUMFGscored = $row['SUMFGscored']; 
		$SUMFGtotal = $row['SUMFGtotal'];
		$SUMFGOscored = $row['SUMFGOscored']; 
		$SUMFGOtotal = $row['SUMFGOtotal'];
		$SUMTHPscored = $row['SUMTHPscored']; 
		$SUMTHPtotal = $row['SUMTHPtotal'];
		$SUMPF = $row['SUMPF'];
		$SUMS5 = $row['SUMS5']; 
		$DNPtot = $row['DNPtot'];
		$TOTALGAMES = $row['TOTALGAMES'];    
		$DNPcoach = $row['DNPcoach'];   
		$DNPinjury = $row['DNPinjury']; 

		$totalgameplayed = $TOTALGAMES - $DNPtot;

		// MINUTES PLAYED CORRECT NOTATION
		$minutesplayed = floor((int)$row['SUMMP'] / 60);
  		$seconds = (int)$row['SUMMP'] % 60;

		if ( $seconds >= 0 && $seconds < 10) {
			$secondsplayed = "0$seconds";
		} else {
			$secondsplayed = $seconds;
		}

  		$SUMMP = "$minutesplayed:$secondsplayed"; 

		if ($season < '2017/2018') {
		  $totpoints = 2 * $SUMFGscored + $SUMFTscored;
		} else if ($season >= '2017/2018') {
		  $totpoints =  2 * ($SUMFGscored + $SUMFGOscored) + $SUMFTscored + 3 * $SUMTHPscored;
		} 

		if ($totalgameplayed > 0) {

			$DRBAVG = round($SUMDRB/$totalgameplayed);
			$ORBAVG = round($SUMORB/$totalgameplayed);
			$TOAVG = round($SUMTOV/$totalgameplayed);
			$STAVG = round($SUMST/$totalgameplayed);
			$ASTAVG = round($SUMAST/$totalgameplayed);
			$BSAVG = round($SUMBS/$totalgameplayed);
			$PFAVG = round($SUMPF/$totalgameplayed);
			$PTSAVG = round($totpoints/$totalgameplayed);
			$S5AVG = round(($SUMS5/$totalgameplayed)*100);

			// MINUTES PLAYED CORRECT NOTATION
			$MPAVG = round($row['SUMMP']/$totalgameplayed);
			$minutesplayed = floor((int)$MPAVG / 60);
  			$seconds = (int)$MPAVG % 60;

  			if ( $seconds >= 0 && $seconds < 10) {
					$secondsplayed = "0$seconds";
			} else {
					$secondsplayed = $seconds;
			}

  			$MPAVGprint = "$minutesplayed:$secondsplayed";


		} else{
				$DRBAVG = $ORBAVG = $TOAVG = $STAVG = $PFAVG = $PTSAVG = $ASTAVG = $BSAVG =$MPAVGprint = $S5AVG = '';
			}		

		?>

		<div class="row">
				<div class="col-md-12">
					<div class="table-responsive">
					<h4>Total Game <?= $season; ?>  </h4>
					<table class="table table-hover table-striped">
					    <thead>
					      <tr>
					        <th>DRB</th>
					        <th>ORB</th>
					        <th>TO</th>
					        <th>ST</th>
		<?php if ($season >= '2018/2019') { echo "<th>AST</th>";echo "<th>BS</th>"; } ?>
					        
					        
		<?php 
		if ($season < '2017/2018') {
		  echo "<th>FG</th>";
		} else if ($season >= '2017/2018') {
		  echo "<th>FGI</th>";
		  echo "<th>FGO</th>";
		  echo "<th>3P</th>";
		}

		?>					<th>FT</th>
					        <th>PTS</th>
					        <th>PF</th>

					        <?php if ($season >= '2018/2019') { 
					        	echo "<th>MP</th>"; 
					        	echo "<th>S5</th>"; 

					        } ?>

					        <th>DNP</th>
					    </tr>
					    </thead>
					    <tbody>
					   <?php

					   if ($SUMMP == 0) {
					   	echo "<td colspan='15'></td>";
					   	
					   } else {
					   	
					     ?>
					    	<td><?= $SUMDRB; ?>(<?= $DRBAVG; ?>)</td>
					    	<td><?= $SUMORB; ?>(<?= $ORBAVG; ?>)</td>
					    	<td><?= $SUMTOV; ?>(<?= $TOAVG; ?>)</td>
					    	<td><?= $SUMST; ?>(<?= $STAVG; ?>)</td>
		<?php if ($season >= '2018/2019') { echo "<td>$SUMAST($ASTAVG)</td>";echo "<td>$SUMBS($BSAVG)</td>"; } ?>
					    	
					    	


					    	<?php 
					    	if ($season < '2017/2018') {
					    		echo "<td>$SUMFGscored/$SUMFGtotal";
					    		if($SUMFGtotal > 0) { echo "(" . round(($SUMFGscored/$SUMFGtotal)*100) . "%)";} 
								echo "</td>";

		} else if ($season >= '2017/2018') {
						    	echo "<td>$SUMFGscored/$SUMFGtotal";
					    		if($SUMFGtotal > 0) { 
					    			echo "(" . round(($SUMFGscored/$SUMFGtotal)*100) . "%)";} 
									echo "</td>";
									echo "<td>$SUMFGOscored/$SUMFGOtotal";
					    		if($SUMFGOtotal > 0) { 
					    			echo "(" . round(($SUMFGOscored/$SUMFGOtotal)*100) . "%)";} 
									echo "</td>";
									echo "<td>$SUMTHPscored/$SUMTHPtotal";
					    		if($SUMTHPtotal > 0) { 
					    			echo "(" . round(($SUMTHPscored/$SUMTHPtotal)*100) . "%)";} 
									echo "</td>";

								} 

		?>		<td><?= $SUMFTscored; ?>/<?= $SUMFTtotal; ?><?php if($SUMFTtotal > 0) { echo "(" . round(($SUMFTscored/$SUMFTtotal)*100) . "%)";} ?> </td>
					    	<td> <?= $totpoints; ?>(<?= $PTSAVG; ?>)	</td>
					    	<td><?= $SUMPF; ?>(<?= $PFAVG; ?>)</td>

					    	<?php if ($season >= '2018/2019') { 
					        	echo "<td>$SUMMP($MPAVGprint)</td>"; 
					        	echo "<td>$SUMS5/$totalgameplayed($S5AVG%)</td>"; 

					        } ?>

					    	<td><?= $DNPtot; ?>/<?= $TOTALGAMES; ?> (I:<?= $DNPinjury; ?> C:<?= $DNPcoach; ?>)</td>

					    	<?php } ?>

					    </tbody>
					  </table>
					</div>
			</div>
		</div>
		<?php
	}

public function SeasonTrainingStatsPlayer($playerid)
	{
		//require __DIR__ . '/../db_bb_connect.php';

		$sql = "SELECT DISTINCT season 
		FROM teams 
		WHERE playerID = '$playerid'
		ORDER BY season DESC
		LIMIT 1";

		$row = $this->FetchResults($sql);
		$season =  $row['season'];

		$sql = "SELECT DISTINCT week(date) as week, year(date) as year
		FROM trainingpresence 
		WHERE season = '$season'
		ORDER BY year(date) DESC, week(date) DESC
		LIMIT 1";

		$row = $this->FetchResults($sql);
		$week =  $row['week'];
		$year =  $row['year'];

		$sql = "SELECT COUNT(CASE presence WHEN 'yes' THEN 1 ELSE NULL END) AS totalpresence, 
		COUNT(presence) AS totaltraining 
		FROM trainingpresence
		WHERE playerID = '$playerid' 
		AND season = '$season'";

		$row = $this->FetchResults($sql);
		$totalpresence =  $row['totalpresence'];
		$totaltraining =  $row['totaltraining'];

		$sql = "SELECT SUM(ftscored) AS sumftscored, 
		SUM(fttotal) AS sumft 
		FROM trainingft
		WHERE playerID = '$playerid' 
		AND season = '$season'";

		$row = $this->FetchResults($sql);
		$sumftscored =  $row['sumftscored'];
		$sumft =  $row['sumft'];

		$sql = "SELECT COUNT(case ftladderresult when 'yes' then 1 else null end) AS sumftladdermade, 
		COUNT(ftladderresult) AS sumftladdertotal 
		FROM trainingftladder
		WHERE playerID = '$playerid' 
		AND season = '$season'";

		$row = $this->FetchResults($sql);
		$sumftladdermade =  $row['sumftladdermade'];
		$sumftladdertotal =  $row['sumftladdertotal'];

		?>

		<div class="row">
				<div class="col-md-12">
					<h4>Total Training <?= $season ?> </h4>
					</div>
		</div>
		<div class="row">
		<div class="col-md-3"><strong>Presence</strong> <br/>
			<?= $totalpresence ?>/<?= $totaltraining ?> <?php if($totaltraining > 0) { echo "(". round(($totalpresence/$totaltraining)*100) . "%)"; } ?>
		</div>
		<div class="col-md-3"> <strong>FT</strong><br/>
		<?= $sumftscored ?>/<?= $sumft ?> <?php if($sumft > 0) { echo "(". round(($sumftscored/$sumft)*100) . "%)"; } ?> 
		</div>
		<div class="col-md-3"> <strong>FT-ladder</strong> <br/>
			<?= $sumftladdermade ?>/<?= $sumftladdertotal ?> <?php if($sumftladdertotal > 0) { echo "(". round(($sumftladdermade/$sumftladdertotal)*100) . "%)"; } ?> 
		</div>
		<div class="col-md-3"> <strong>Shuttle Run</strong><br/>

		<div class="table-responsive">
			<table class="table table-hover table-striped">
			    <thead>
			      <tr>
			    </tr>
			    </thead>
			    <tbody>
		<?php 

		$sql = "SELECT date, trap 
		FROM trainingshuttlerun
		WHERE playerID = '$playerid'
		AND NOT trap = 0
		AND season = '$season'
		ORDER BY date DESC";

		require __DIR__ . '/../db_bb_connect.php';

		if ($db->query($sql)) {  

		$result = $db->query($sql);
		while ($row = $result->fetch_assoc()) {
			$date =  $row['date'];
			$trap =  $row['trap'];
			echo "<tr><td> $date </td>";
			echo "<td> $trap </td></tr>";
		}
		} else {
      		echo "Error: " . $sql . "<br>" . $db->error;
    		}  



		?>
			    	 </tbody>
			  </table>
		</div>




		</div>
		</div>
		<?php
	}

public function LastTrainingStatsPlayer($playerid)
	{

		//require __DIR__ . '/../db_bb_connect.php';

		$sql = "SELECT DISTINCT season 
		FROM teams 
		WHERE playerID = '$playerid'
		ORDER BY season DESC
		LIMIT 1";

		$row = $this->FetchResults($sql);
		$season =  $row['season'];

		$sql = "SELECT DISTINCT week(date,3) as week, year(date) as year
		FROM trainingpresence 
		WHERE season = '$season'
		ORDER BY year(date) DESC, week(date,3) DESC
		LIMIT 1";

		$row = $this->FetchResults($sql);
		$week =  $row['week'];
		$year =  $row['year'];

		$sql = "SELECT COUNT(CASE presence WHEN 'yes' THEN 1 ELSE NULL END) AS totalpresence, 
		COUNT(presence) AS totaltraining 
		FROM trainingpresence
		WHERE playerID = '$playerid' 
		AND season = '$season' 
		AND WEEK(date,3) = '$week'
		AND YEAR(date) = '$year'";

		$row = $this->FetchResults($sql);
		$totalpresence =  $row['totalpresence'];
		$totaltraining =  $row['totaltraining'];

		$sql = "SELECT SUM(ftscored) AS sumftscored, 
		SUM(fttotal) AS sumft 
		FROM trainingft
		WHERE playerID = '$playerid' 
		AND season = '$season' 
		AND WEEK(date,3) = '$week'
		AND YEAR(date) = '$year'";

		$row = $this->FetchResults($sql);
		$sumftscored =  $row['sumftscored'];
		$sumft =  $row['sumft'];

		$sql = "SELECT COUNT(case ftladderresult when 'yes' then 1 else null end) AS sumftladdermade, 
		COUNT(ftladderresult) AS sumftladdertotal 
		FROM trainingftladder
		WHERE playerID = '$playerid' 
		AND season = '$season'		
		AND WEEK(date,3) = '$week'
		AND YEAR(date) = '$year'";

		$row = $this->FetchResults($sql);
		$sumftladdermade =  $row['sumftladdermade'];
		$sumftladdertotal =  $row['sumftladdertotal'];

		$sql = "SELECT date, trap 
		FROM trainingshuttlerun
		WHERE playerID = '$playerid'
		AND NOT trap = 0
		AND season = '$season'
		AND WEEK(date,3) = '$week'
		AND YEAR(date) = '$year'
		LIMIT 1";

		$row = $this->FetchResults($sql);

		$date =  $row['date'];
		$trap =  $row['trap'];


		?>

		<div class="row">
				<div class="col-md-12">
					<h4>Last Week Training (week <?= $week ?> of <?= $year ?>)  </h4>

					</div>
		</div>
		<div class="row">
		<div class="col-md-3">
			<strong>Presence</strong><br/>
		<?= $totalpresence; ?>/<?= $totaltraining; ?> 
		</div>
		<div class="col-md-3"> 
			<strong>FT</strong> <br/>

			<?php if($sumft > 0) { 
				echo "$sumftscored/$sumft(". round(($sumftscored/$sumft)*100) . "%)"; 
			} else {
				echo "-";
			} ?> 
		</div>
		<div class="col-md-3"> <strong>FT-ladder</strong> <br/>
		<?php if($sumftladdertotal != 0 ){ 
			echo $sumftladdermade . "/" . $sumftladdertotal;
			echo "(" . round(($sumftladdermade/$sumftladdertotal)*100) . ")%";
		} else { 
			echo "-";
		} ?>
		</div>
		<div class="col-md-3"> <strong>Shuttle Run</strong> <br/>

		<?php
		if ($trap) {
			echo $date . " " . $trap;
		} else {
			echo "-";
		}
		
		?>

		</div>
		</div>

		<?php
	}

public function ShowAttentionpointsPlayer($playerid, $category)
	{

		$sql = "SELECT text
			    FROM attentionpointsplayers
			    WHERE playerID = '$playerid'
			    AND category = '$category'
			    AND visibility = 'yes'";

		require __DIR__ . '/../db_bb_connect.php';

		if ($db->query($sql)) {  
			$result = $db->query($sql);
			while ($row = $result->fetch_assoc()) {
				$text = nl2br($row['text']);
				echo "<li> $text </li>";
				}		
		} else {
      		echo "Error: " . $sql . "<br>" . $db->error;
    		}  
	}

public function ShowAttentionpointsTeam($category, $playerID)
	{
		require __DIR__ . '/../db_bb_connect.php';
		
		$sql="SELECT teams.season
		  FROM users
		  JOIN teams
		  ON users.user_key = teams.playerID
		  WHERE users.user_key = '$playerID'
		  ORDER BY teams.season DESC
		  LIMIT 1";

		  if ($db->query($sql)) {  
		    } else {
		      echo "Error: " . $sql . "<br>" . $db->error;
		    }

		  $result = $db->query($sql);
		  $row = $result->fetch_assoc();
		  $maxseason = $row['season'];

		  $sql = "SELECT enddate, begindate
		  FROM seasons
		  WHERE season = '$maxseason'";  

		    if ($db->query($sql)) {  
		    } else {
		      echo "Error: " . $sql . "<br>" . $db->error;
		    }

		  $result = $db->query($sql);
		  $row = $result->fetch_assoc();
		  $maxdate = $row['enddate'];
		  $mindate = $row['begindate'];

		$sql = "SELECT text
			    FROM attentionpointsteams
			    WHERE category = '$category'
			    AND visibility = 'yes'
			    AND date_create BETWEEN '$mindate' AND '$maxdate'";

		if ($db->query($sql)) {  
			$result = $db->query($sql);
			while ($row = $result->fetch_assoc()) {
				$text = nl2br($row['text']);
				echo "<li> $text </li>";
				}		
		} else {
      		echo "Error: " . $sql . "<br>" . $db->error;
    		}  
	}

public function ShowAttentionpointsCurrentTeam($category)
	{
		require __DIR__ . '/../db_bb_connect.php';
		
		$sql="SELECT season
		  FROM teams
		  ORDER BY season DESC
		  LIMIT 1";

		  if ($db->query($sql)) {  
		    } else {
		      echo "Error: " . $sql . "<br>" . $db->error;
		    }

		  $result = $db->query($sql);
		  $row = $result->fetch_assoc();
		  $maxseason = $row['season'];

		  $sql = "SELECT enddate, begindate
		  FROM seasons
		  WHERE season = '$maxseason'";  

		    if ($db->query($sql)) {  
		    } else {
		      echo "Error: " . $sql . "<br>" . $db->error;
		    }

		  $result = $db->query($sql);
		  $row = $result->fetch_assoc();
		  $maxdate = $row['enddate'];
		  $mindate = $row['begindate'];

		$sql = "SELECT text
			    FROM attentionpointsteams
			    WHERE category = '$category'
			    AND visibility = 'yes'
			    AND date_create BETWEEN '$mindate' AND '$maxdate'";

		echo "<h4> $category </h4>";

		if ($db->query($sql)) {  
			$result = $db->query($sql);
			while ($row = $result->fetch_assoc()) {
				$text = nl2br($row['text']);
				echo "<li>$text </li>";
				}		
		} else {
      		echo "Error: " . $sql . "<br>" . $db->error;
    		}  
	}

public function LastGameStatsCurrentTeam()
	{
		require __DIR__ . '/../db_bb_connect.php';

		$sql="SELECT season
		  FROM teams
		  ORDER BY season DESC
		  LIMIT 1";

		if ($db->query($sql)) {  
		    } else {
		      echo "Error: " . $sql . "<br>" . $db->error;
		    }

		$result = $db->query($sql);
		$row = $result->fetch_assoc();
		$maxseason = $row['season'];

		$sql="SELECT gamenumber
		  FROM stats
		  WHERE season = '$maxseason'
		  ORDER BY gamenumber DESC
		  LIMIT 1";

		if ($db->query($sql)) {  
		    } else {
		      echo "Error: " . $sql . "<br>" . $db->error;
		    }

		$result = $db->query($sql);
		$row = $result->fetch_assoc();
		$gamenumber = $row['gamenumber'];

		$sql="SELECT date, opponent, location, score_exc_tot,score_opp_tot
		  FROM games
		  WHERE season = '$maxseason'
		  AND gamenumber = '$gamenumber'";

		if ($db->query($sql)) {  
		    } else {
		      echo "Error: " . $sql . "<br>" . $db->error;
		    }

		$result = $db->query($sql);
		$row = $result->fetch_assoc();

		$date = $row['date'];
		$opponent = $row['opponent'];
		$location = $row['location'];
		$score_exc_tot = $row['score_exc_tot'];
		$score_opp_tot = $row['score_opp_tot'];


		?>
		<div class="table-responsive cumustatstable">
			<h4>Stats of Last Game - <?= $opponent ?> <?= $location ?>: <?= $score_exc_tot ?>-<?= $score_opp_tot ?> on <?= $date ?>  </h4>

			 <button type="button" class="btn btn-default" id="loadallgamestatslast">Load All Game Stats</button>
          <div id="allgamestatslast"></div>

          <script type="text/javascript">
				$(document).on("click","#loadallgamestatslast", function() {
				    $.ajax({
				      type: "POST",
				      url: "./stats_game.php",
				      data: { season: '<?= $maxseason; ?>', gamenumber : '<?= $gamenumber; ?>', date : '<?= $date; ?>', opponent : '<?= $opponent; ?>', location : '<?= $location; ?>'  },
				      success: function(data) {
				        $("#allgamestatslast").html(data);
				      }
				  }); 
				  return false;
				});
		</script>
				<table class="table table-hover table-striped">
		    <thead>
		      <tr>
		        <th>DRB</th>
		        <th>ORB</th>
		        <th>TO</th>
		        <th>ST</th>		        
		        <th>AST</th>
		        <th>BS</th>		        
		        <th>FGI</th>
		        <th>FGO</th>
		        <th>3P</th>		        
		        <th>FT</th>
		        <th>PTS</th>
		        <th>PF</th>
		        
		      </tr>
		    </thead>
		    <tbody>

		<?php 
		    	$sql = "SELECT SUM(DRB) AS DRBtot, 
		SUM(ORB) AS ORBtot, 
		SUM(TOV) AS TOVtot,
		SUM(ST) AS STtot,
		SUM(AST) AS ASTtot,
		SUM(BS) AS BStot,
		SUM(FTscored) AS FTscoredtot, 
		SUM(FTtotal) AS FTtottot,
		SUM(FGscored) AS FGscoredtot,
		SUM(FGtotal) AS FGtottot,
		SUM(FG_outside_scored) AS FG_outside_scoredtot,
		SUM(FG_outside_total) AS FG_outside_totaltot,
		SUM(THPscored) AS THPscoredtot,
		SUM(THPtotal) AS THPtotaltot,
		SUM((2 * FGscored) + FTscored) AS PTStotOLD, 
		SUM( (2 * FGscored) + (2 * FG_outside_scored) + FTscored + (3 * THPscored)) AS PTStotNEW, 
		SUM(PF) AS PFtot
		FROM stats
		WHERE season = '$maxseason'
		AND gamenumber = '$gamenumber'";

		$result=$db->query($sql);
		$row=$result->fetch_assoc();

		$DRBtot = $row['DRBtot'];
		$ORBtot = $row['ORBtot'];
		$TOVtot = $row['TOVtot'];
		$STtot = $row['STtot'];
		$ASTtot = $row['ASTtot'];
		$BStot = $row['BStot'];
		$FTscoredtot = $row['FTscoredtot'];
		$FTtottot = $row['FTtottot'];

		$FGscoredtot = $row['FGscoredtot'];
		$FGtottot = $row['FGtottot'];
		$FG_outside_scoredtot = $row['FG_outside_scoredtot'];
		$FG_outside_totaltot = $row['FG_outside_totaltot'];
		$THPscoredtot = $row['THPscoredtot'];
		$THPtotaltot = $row['THPtotaltot'];

		$PTStotOLD = $row['PTStotOLD'];
		$PTStotNEW = $row['PTStotNEW'];

		$PFtot = $row['PFtot'];

		if($FTtottot != 0){
		    $FTperc = $FTscoredtot/$FTtottot;
		  } else{
		    $FTperc = 0;
		  }

		  if($FGtottot != 0){
		    $FGperc = $FGscoredtot/$FGtottot;
		  } else{
		    $FGperc = 0;
		  }

		  if($FG_outside_totaltot != 0){
		    $FGOperc = $FG_outside_scoredtot/$FG_outside_totaltot;
		  } else{
		    $FGOperc = 0;
		  }

		  if($THPtotaltot != 0){
		    $THPperc = $THPscoredtot/$THPtotaltot;
		  } else{
		    $THPperc = 0;
		  }


		echo "<tr>";   
		echo "<td>  $DRBtot </td>";
		echo "<td>  $ORBtot </td>";
		echo "<td>  $TOVtot</td>";
		echo "<td>  $STtot</td>";
		echo "<td>  $ASTtot</td>";
		echo "<td>  $BStot</td>";		
		echo "<td>  $FGscoredtot / $FGtottot <br>(" . round($FGperc *100) ."%)</td>";
		echo "<td>$FG_outside_scoredtot/$FG_outside_totaltot <br>(" . round($FGOperc *100) ."%)</td>";
		echo "<td>$THPscoredtot/$THPtotaltot <br>(" . round($THPperc *100) ."%)</td>";
		echo "<td>  $FTscoredtot / $FTtottot <br>(" . round($FTperc *100) ."%)</td>";
		echo "<td> $PTStotNEW </td>";
		echo "<td>  $PFtot</td>";

		echo "</tr>";

		?>



		    </tbody>
		</table>
		</div>
				
		<?php
	}

public function SeasonGameStatsCurrentTeam()
	{
		require __DIR__ . '/../db_bb_connect.php';

		$sql="SELECT season
		  FROM teams
		  ORDER BY season DESC
		  LIMIT 1";

		if ($db->query($sql)) {  
		    } else {
		      echo "Error: " . $sql . "<br>" . $db->error;
		    }

		$result = $db->query($sql);
		$row = $result->fetch_assoc();
		$maxseason = $row['season'];
		?>

		<div class="table-responsive cumustatstable">
		<h4>Cumulative Stats of <?= $maxseason; ?></h4>

		<button type="button" class="btn btn-default" id="loadallgamestatsseason">Load All Season Stats</button>
          <div id="allgamestatsseason"></div>

          <script type="text/javascript">
				$(document).on("click","#loadallgamestatsseason", function(){
				    $.ajax({
				      type: "POST",
				      url: "./game_stats_archive_cumustatstable.php",
				      data: { season: '<?= $maxseason; ?>' },
				      success: function(data) {
				        $("#allgamestatsseason").html(data);
				      }
				  }); 
				  return false;
				});


		</script>


		<table class="table table-hover table-striped">
    	<thead>
      	<tr>
        <th>DRB</th>
        <th>ORB</th>
        <th>TO</th>
        <th>ST</th>
        <th>AST</th>
        <th>BS</th>
        <th>FGI</th>
        <th>FGO</th>
        <th>3P</th>
        <th>FT</th>
        <th>PTS</th>
        <th>PF</th>
      	</tr>
    	</thead>
    	<tbody>

		<?php
		    	$sql = "SELECT SUM(ORB) AS SUMORB,
			SUM(DRB) AS SUMDRB,
			SUM(TOV) AS SUMTOV,
			SUM(PF) AS SUMPF,
			SUM(ST) AS SUMST,
			SUM(AST) AS SUMAST,
			SUM(BS) AS SUMBS,
			SUM(FTscored) AS SUMFTscored,
			SUM(FTtotal) AS SUMFTtotal,
			SUM(FGscored) AS SUMFGscored,
			SUM(FGtotal) AS SUMFGtotal,
			SUM(FG_outside_scored) AS SUMFG_outside_scored,
			SUM(FG_outside_total) AS SUMFG_outside_total,
			SUM(THPscored) AS SUMTHPscored,
			SUM(THPtotal) AS SUMTHPtotal,
			count(DNP) AS totalgamestatsavailable,
			COUNT(DISTINCT gamenumber) AS totalgamestats
		FROM stats 
		WHERE season = '$maxseason'";

		$result=$db->query($sql);
		$row=$result->fetch_assoc();

			$SUMORB = $row['SUMORB'];
			$SUMDRB = $row['SUMDRB'];
			$SUMTOV = $row['SUMTOV'];
			$SUMST = $row['SUMST'];
			$SUMAST = $row['SUMAST'];
			$SUMBS = $row['SUMBS'];
			$SUMPF = $row['SUMPF'];
			$SUMFTtotal = $row['SUMFTtotal'];
			$SUMFTscored = $row['SUMFTscored'];

			$SUMFGscored = $row['SUMFGscored'];
			$SUMFGtotal = $row['SUMFGtotal'];

			$SUMFG_outside_scored = $row['SUMFG_outside_scored'];
			$SUMFG_outside_total = $row['SUMFG_outside_total'];

			$SUMTHPscored = $row['SUMTHPscored'];
			$SUMTHPtotal = $row['SUMTHPtotal'];

			$totalgamestatsavailable = $row['totalgamestatsavailable'];
			$totalgamestats = $row['totalgamestats'];
			
			if($SUMFTtotal != 0){
				$FTperc = $SUMFTscored/$SUMFTtotal;
			} else {
				$FTperc = 0;
			}

			if($SUMFGtotal != 0){
				$FGperc = $SUMFGscored/$SUMFGtotal;
			} else{
				$FGperc = 0;
			}

			if($SUMFG_outside_total != 0){
				$FGOperc = $SUMFG_outside_scored/$SUMFG_outside_total;
			} else{
				$FGOperc = 0;
			}

				if($SUMTHPtotal != 0){
				$THPperc = $SUMTHPscored/$SUMTHPtotal;
			} else{
				$THPperc = 0;
			}



			$totpointsOLD = (2*$SUMFGscored)+$SUMFTscored;
			$totpointsNEW = (2* ($SUMFGscored + $SUMFG_outside_scored))+$SUMFTscored + 3 * $SUMTHPscored;
			$DRBAVG = round($SUMDRB/$totalgamestats);
			$ORBAVG = round($SUMORB/$totalgamestats);
			$TOAVG = round($SUMTOV/$totalgamestats);
			$STAVG = round($SUMST/$totalgamestats);
			$ASTAVG = round($SUMAST/$totalgamestats);
			$BSAVG = round($SUMBS/$totalgamestats);
			$PFAVG = round($SUMPF/$totalgamestats);
			$PTSAVG = round($totpointsNEW/$totalgamestats);



		echo "<tr>";

			echo "
			<td>$SUMDRB($DRBAVG)</td> 
			<td>$SUMORB($ORBAVG)</td> 
			<td>$SUMTOV($TOAVG)</td> 
			<td>$SUMST($STAVG)</td>
			<td>$SUMAST($ASTAVG)</td> 
			<td>$SUMBS($BSAVG)</td> 			 
			";
		  echo "<td>$SUMFGscored/$SUMFGtotal(". round(($FGperc)*100) ."%)</td>";
		  echo "<td>$SUMFG_outside_scored/$SUMFG_outside_total(". round(($FGOperc)*100) ."%)</td>";
		  echo "<td>$SUMTHPscored/$SUMTHPtotal(". round(($THPperc)*100) ."%)</td>";
		  echo "<td>$SUMFTscored/$SUMFTtotal(". round(($FTperc)*100) ."%)</td>";
		  echo "<td>$totpointsNEW($PTSAVG)</td>";
		  echo "<td>$SUMPF($PFAVG)</td>";

		  echo "</tr>";

		?>
		    </tbody>
		</table>
		</div>

		<?php
	}

public function LastWeekTrainingStatsCurrentTeam()
	{
		echo "LastWeekTrainingStatsCurrentTeam";
	}

public function SeasonTrainingStatsCurrentTeam()
	{
		echo "SeasonTrainingStatCurrentTeam";
	}

public function LastWeekTrainingPresenceCurrentTeam()
	{
		require __DIR__ . '/../db_bb_connect.php';

		$sql="SELECT season
		  FROM teams
		  ORDER BY season DESC
		  LIMIT 1";

		if ($db->query($sql)) {  
		    } else {
		      echo "Error: " . $sql . "<br>" . $db->error;
		    }

		$result = $db->query($sql);
		$row = $result->fetch_assoc();
		$maxseason = $row['season'];

		$sql = "SELECT week(date,3) AS lastweek
		FROM trainingpresence 
		WHERE season = '$maxseason'
		ORDER BY year(date) DESC, week(date,3) DESC
		LIMIT 1";

		if ($db->query($sql)) {  
		    } else {
		      echo "Error: " . $sql . "<br>" . $db->error;
		    }

		$result = $db->query($sql);
		$row = $result->fetch_assoc();
		$lastweek = $row['lastweek'];

		?>

		<script type="text/javascript">
  
		$("document").ready(function() {
		    $.ajax({
		        type: "POST",
		        url: "./training_viewpresenceweek.php",
		        data: { season: "<?= $maxseason ?>", week: "<?= $lastweek ?>"},
		        success: function(data) { 
		            $("#presence").html(data); 
		        },
		        error: function (xhr, status, error) {
		          $("#presence").html(xhr.responseText); 
		        }
		      }); 
		    return false;
		});  

		</script>

		<?php
	}

public function LoginHistoryCurrentTeam()
	{
		require __DIR__ . '/../db_bb_connect.php';

		$sql="SELECT season
		  FROM teams
		  ORDER BY season DESC
		  LIMIT 1";

		if ($db->query($sql)) {  
		    } else {
		      echo "Error: " . $sql . "<br>" . $db->error;
		    }

		$result = $db->query($sql);
		$row = $result->fetch_assoc();
		$maxseason = $row['season'];

		$sql="SELECT t1.firstname, t1.lastname, t2.timestamp FROM users AS t1
		  JOIN teams AS t3 ON t1.user_key = t3.playerID
		  JOIN (SELECT user_key, max(timestamp) AS timestamp FROM serverlog GROUP BY user_key) AS t2 ON (t2.user_key = t1.user_key)
		  WHERE t3.season = '$maxseason'
		  ORDER BY t2.timestamp DESC";

		if ($db->query($sql)) {  
		    } else {
		      echo "Error: " . $sql . "<br>" . $db->error;
		    }

		$sql2 = "SELECT DISTINCT serverlog.user_key, count(serverlog.user_key) AS totallogins FROM serverlog 
		JOIN teams on teams.playerID = serverlog.user_key
		JOIN users on users.user_key = serverlog.user_key
		WHERE teams.season = '$maxseason' AND serverlog.type = 'insert'
		GROUP BY serverlog.user_key ORDER BY max(serverlog.timestamp) DESC";

		if ($db->query($sql2)) {  
		    } else {
		      echo "Error: " . $sql2 . "<br>" . $db->error;
		    }

		$result = $db->query($sql); 
		$result2 = $db->query($sql2); 

		?>

	    <div class="table-responsive cumustatstable">
			<table class="table table-hover table-striped">
		    	<thead>
			      	<tr>
				        <th colspan="2">Name</th>
				        <th>Last Login</th>
				        <th>Total Logins</th>
			      	</tr>
		    	</thead>
	    	<tbody>
	    		
		<?php

		while ($row = $result->fetch_assoc() AND $row2 = $result2->fetch_assoc() ) {
			$firstname = $row['firstname'];
			$lastname = $row['lastname'];
			$timestamp = $row['timestamp'];

			$totallogins = $row2['totallogins'];


			echo "<tr>";
			echo "<td> $firstname </td>";
			echo "<td> $lastname </td>";
			echo "<td> $timestamp </td>";
			echo "<td> $totallogins</td>";
			echo "</tr>";
			
		}

		?>
	    	</tbody>
    		</table>
		</div>


		<?php
	}

public function ClickHistoryCurrentTeam()
	{
		require __DIR__ . '/../db_bb_connect.php';

		$sql="SELECT season
		  FROM teams
		  ORDER BY season DESC
		  LIMIT 1";

		if ($db->query($sql)) {  
		    } else {
		      echo "Error: " . $sql . "<br>" . $db->error;
		    }

		$result = $db->query($sql);
		$row = $result->fetch_assoc();
		$maxseason = $row['season'];

		$username = $_SESSION['username'];

		$coach_user_key = $this->GetUserkeyFromUsername($username);

		$coachteamID = $this->GetCurrentTeamIDFromCoachKey($coach_user_key);

		$sql = "SELECT * FROM clicked_items WHERE user_key IN (SELECT playerID FROM teams WHERE teamID = '$coachteamID' AND season = '$maxseason') ORDER BY timestamp DESC LIMIT 100";

		if ($db->query($sql)) {  
		    } else {
		      echo "Error: " . $sql . "<br>" . $db->error;
		    }

		$result = $db->query($sql);

		while ($row = $result->fetch_assoc()) {
			$date = $row['timestamp'];
			$user_key = $row['user_key'];
			$userfirstname = $this->GetUserFirstnameFromUserkey($user_key);
			$userlastname = $this->GetUserLastnameFromUserkey($user_key);
			$item = ucwords(str_replace("_"," ",$row['clicked_item']));
			echo  "$date - $userfirstname $userlastname - $item <br>";
		}
	}

public function ShowPersonalActionpoints()
	{ 
		require __DIR__ . '/../db_bb_connect.php';

		$sql="SELECT season
		  FROM teams
		  ORDER BY season DESC
		  LIMIT 1";

		if ($db->query($sql)) {  
		    } else {
		      echo "Error: " . $sql . "<br>" . $db->error;
		    }

		$result = $db->query($sql);
		$row = $result->fetch_assoc();
		$maxseason = $row['season'];

		$sql = "SELECT week(date,3) AS lastweek
		FROM trainingpresence 
		WHERE season = '$maxseason'
		ORDER BY year(date) DESC, week(date,3) DESC
		LIMIT 1";

		if ($db->query($sql)) {  
		    } else {
		      echo "Error: " . $sql . "<br>" . $db->error;
		    }

		$result = $db->query($sql);
		$row = $result->fetch_assoc();
		$lastweek = $row['lastweek'];

		?>

		<script type="text/javascript">
  
		$("document").ready(function(){
		    $.ajax({
		        type: "POST",
		        url: "./player_actionpoints.php",
		        data: { season: "<?= $maxseason ?>"},
		        success: function(data) { 
		            $("#personalactionpoints").html(data); 
		        },
		        error: function (xhr, status, error) {
		          $("#personalactionpoints").html(xhr.responseText); 
		        }
		      }); 
		      return false;
		});  

		</script>
		<?php
	} 

public function GetTopStatsPlayersAvg($stattype, $season, $amounttoshow)
	{

		require __DIR__ . '/db_bb_connect.php';

		$sql = "SELECT playerID, SUM($stattype)/COUNT(CASE WHEN DNP = 'no' THEN 1 END) AS AVG, COUNT(CASE WHEN DNP = 'no' THEN 1 END) AS GP FROM stats WHERE season = '$season' AND playerID != 'team' AND playerID IN (SELECT teams.playerID FROM users JOIN teams ON teams.playerID = users.user_key WHERE teams.playertype = 'player') GROUP BY playerID ORDER BY SUM($stattype)/COUNT(CASE WHEN DNP = 'no' THEN 1 END) DESC LIMIT $amounttoshow";

		if ($db->query($sql)) {  
	    } else {
	      //echo "Error: " . $sql . "<br>" . $db->error;
	    }

	    $result = $db->query($sql);

	    $statnames = array('DRB' => 'DRB', 'ORB' => 'ORB', 'TOV'=>'TO','ST'=>'ST','BS'=>'BS','AST'=>'AST','FGscored'=>'FGI scored','FGtotal'=>'FGI total','FG_outside_scored'=>'FGO scored','FG_outside_total'=>'FGO total','THPscored'=>'3P scored','THPtotal'=>'3P total','FTscored'=>' FT scored','FTtotal'=>'FT total','MP'=>'MP','PF'=>'PF');

	    echo "<strong>". $statnames[$stattype] . " </strong><br>";  

	 	 while ( $row = $result->fetch_assoc()) {

			$playerID = $row['playerID'];
		  	$AVG = round($row['AVG'],2);
			$GP = $row['GP'];

		  	$sql = "SELECT firstname, lastname FROM users WHERE user_key = '$playerID'";

			if ($db->query($sql)) {  
			} else {
				//echo "Error: " . $sql . "<br>" . $db->error;
			}

			$result2 = $db->query($sql);
			$row2 = $result2->fetch_assoc();

			$firstname = $row2['firstname']; 
			$lastname = $row2['lastname']; 

			if ($stattype == 'MP') {
				$minutesplayed = floor((int)$AVG / 60);
				$seconds = (int)$AVG % 60;

				if ( $seconds >= 0 && $seconds < 10) {
					$secondsplayed = "0$seconds";
				} else {
					$secondsplayed = $seconds;
				}

				$AVG = "$minutesplayed:$secondsplayed";
			}
		  	echo  "$firstname $lastname $AVG ($GP) <br>";
			}
	}

public function GetTopStatsPlayersSum($stattype, $season, $amounttoshow)
	{

		require __DIR__ . '/db_bb_connect.php';

		$sql = "SELECT playerID, SUM($stattype) AS SUM, COUNT(CASE WHEN DNP = 'no' THEN 1 END) AS GP FROM stats WHERE season = '$season' AND playerID != 'team' AND playerID IN (SELECT teams.playerID FROM users JOIN teams ON teams.playerID = users.user_key WHERE teams.playertype = 'player') GROUP BY playerID ORDER BY SUM($stattype) DESC LIMIT $amounttoshow";

		if ($db->query($sql)) {  
	    } else {
	      //echo "Error: " . $sql . "<br>" . $db->error;
	    }

	    $result = $db->query($sql);

	    $statnames = array('DRB' => 'DRB', 'ORB' => 'ORB', 'TOV'=>'TO','ST'=>'ST','BS'=>'BS','AST'=>'AST','FGscored'=>'FGI scored','FGtotal'=>'FGI total','FG_outside_scored'=>'FGO scored','FG_outside_total'=>'FGO total','THPscored'=>'3P scored','THPtotal'=>'3P total','FTscored'=>' FT scored','FTtotal'=>'FT total','MP'=>'MP','PF'=>'PF');

	    echo "<strong>". $statnames[$stattype] . " </strong><br>";  

	  	while ( $row = $result->fetch_assoc()) {

			$playerID = $row['playerID'];
		  	$SUM = $row['SUM'];
		  	$GP = $row['GP'];

		  	$sql = "SELECT firstname, lastname FROM users WHERE user_key = '$playerID'";

			if ($db->query($sql)) {  
			} else {
				//echo "Error: " . $sql . "<br>" . $db->error;
			}

			$result2 = $db->query($sql);
			$row2 = $result2->fetch_assoc();

			$firstname = $row2['firstname']; 
			$lastname = $row2['lastname']; 

			if ($stattype == 'MP') {
				$minutesplayed = floor((int)$SUM / 60);
				$seconds = (int)$SUM % 60;

				if ( $seconds >= 0 && $seconds < 10) {
					$secondsplayed = "0$seconds";
				} else {
					$secondsplayed = $seconds;
				}

				$SUM = "$minutesplayed:$secondsplayed";
			}
	  		echo  "$firstname $lastname $SUM ($GP)<br>";
		}
	}

public function GetTopStatsPlayersAvgMinute($stattype, $season, $amounttoshow)
	{

		require __DIR__ . '/db_bb_connect.php';

		$sql = "SELECT playerID, SUM($stattype)/SUM(MP) AS AVG, SUM(MP) AS SUMMP FROM stats WHERE season = '$season' AND playerID != 'team' AND playerID IN (SELECT teams.playerID FROM users JOIN teams ON teams.playerID = users.user_key WHERE teams.playertype = 'player') GROUP BY playerID ORDER BY SUM($stattype)/SUM(MP) DESC LIMIT $amounttoshow";

		if ($db->query($sql)) {  
	    } else {
	      //echo "Error: " . $sql . "<br>" . $db->error;
	    }

	    $result = $db->query($sql);

	    $statnames = array('DRB' => 'DRB', 'ORB' => 'ORB', 'TOV'=>'TO','ST'=>'ST','BS'=>'BS','AST'=>'AST','FGscored'=>'FGI scored','FGtotal'=>'FGI total','FG_outside_scored'=>'FGO scored','FG_outside_total'=>'FGO total','THPscored'=>'3P scored','THPtotal'=>'3P total','FTscored'=>' FT scored','FTtotal'=>'FT total','MP'=>'MP','PF'=>'PF');

	    echo "<strong>". $statnames[$stattype] . " </strong><br>";  

	 	while ( $row = $result->fetch_assoc()) {

			$playerID = $row['playerID'];
		  	$AVG = 60 * round($row['AVG'],4);

		  	$SUMMP = round($row['SUMMP'] / 60);

		  	$sql = "SELECT firstname, lastname FROM users WHERE user_key = '$playerID'";

			if ($db->query($sql)) {  
			} else {
				//echo "Error: " . $sql . "<br>" . $db->error;
			}

			$result2 = $db->query($sql);
			$row2 = $result2->fetch_assoc();

			$firstname = $row2['firstname']; 
			$lastname = $row2['lastname']; 

		 	echo  "$firstname $lastname $AVG ($SUMMP)<br>";
		}
	}

public function GetCurrentTeamBirthdaysFromPlayerID($player_user_key, $amounttoshow)
	{
		require __DIR__ . '/db_bb_connect.php';

		$sql="SELECT season, teamID
		FROM teams
		WHERE playerID = '$player_user_key'
		ORDER BY season DESC
		LIMIT 1";

		if ($db->query($sql)) {  
		} else {
			echo "Error: " . $sql . "<br>" . $db->error;
		}

		$result = $db->query($sql);
		$row = $result->fetch_assoc();
		$playermaxseason = $row['season'];
		$teamID = $row['teamID'];

		// get all playerIDs and coachIDs from coached team and get their firstame, lastname, birthdate 

		$sql = "SELECT users.firstname, users.lastname, users.birthdate, MONTH(users.birthdate) AS m, DAY(users.birthdate) AS d FROM users 
		WHERE users.user_key 
		IN ( SELECT teams.playerID FROM teams JOIN users ON users.user_key = teams.playerID WHERE teams.teamID = '$teamID' AND teams.season = '$playermaxseason' AND users.type = 'Player' AND teams.playertype != 'bench')
		OR users.user_key 
		IN ( SELECT coach_user_key FROM coach_teams WHERE teamID = '$teamID' AND season = '$playermaxseason' )
		ORDER BY (m,d) < ( MONTH(CURDATE()), DAY(CURDATE()) )
       , m
       , d ASC LIMIT $amounttoshow";

	  	if ($db->query($sql)) {  
	    } else {
	      echo "Error: " . $sql . "<br>" . $db->error;
	    }

	  	$result = $db->query($sql);

	  	echo '
		<div class="table-responsive">
		<table class="table table-striped">
		<thead>
		</thead>
		<tbody>';

	  	while ( $row = $result->fetch_assoc()) {

			$firstname = $row['firstname']; 
			$lastname = $row['lastname']; 
			$birthdate = $row['birthdate']; 

			$m = date('M', strtotime($birthdate));
			$d = date('d', strtotime($birthdate));
			$datethisyear = date('Y') . "-" . date('m', strtotime($birthdate)) . "-$d";
			$weekdaythisyear = date('D', strtotime($datethisyear));

			$timestampconv = strtotime($birthdate);
			$date = date("dS M Y", $timestampconv);
			$datebirth = new DateTime($date);
			$datetoday = new DateTime("now");
			
			$mtoday = date('M');
			$dtoday = date('d');

			if ($m == $mtoday && $d == $dtoday ) {
				$interval = $datetoday->diff($datebirth);
		  		$age = $interval->y;
				echo "<tr> <td colspan='2' class='text-center'> <h4><strong> Today $firstname $lastname has become $age!</strong></h4> <td></tr>";
			} else {
				
				$interval = $datetoday->diff($datebirth);
		  		$age = $interval->y + 1;

		  		echo "<tr> 
		  		<td> $weekdaythisyear $d $m </td> 
		  		<td> $firstname $lastname </td> 
		  		<td> $age </td>
		  		</tr>";
			}

		}
			  		echo '</tbody>
		</table>
		</div>';
	}

public function GetCurrentTeamBirthdaysFromCoachID($coach_user_key, $amounttoshow)
	{
		require __DIR__ . '/db_bb_connect.php';

		$sql="SELECT season, teamID
		FROM coach_teams
		WHERE coach_user_key = '$coach_user_key'
		ORDER BY season DESC
		LIMIT 1";

		if ($db->query($sql)) {  
		} else {
			echo "Error: " . $sql . "<br>" . $db->error;
		}

		$result = $db->query($sql);
		$row = $result->fetch_assoc();
		$coachmaxseason = $row['season'];
		$teamID = $row['teamID'];

		// get all playerIDs and coachIDs from coached team and get their firstame, lastname, birthdate 

		$sql = "SELECT users.firstname, users.lastname, users.birthdate, MONTH(users.birthdate) AS m, DAY(users.birthdate) AS d FROM users 
		WHERE users.user_key 
		IN ( SELECT teams.playerID FROM teams JOIN users ON users.user_key = teams.playerID WHERE teams.teamID = '$teamID' AND teams.season = '$coachmaxseason' AND users.type = 'Player' AND teams.playertype != 'bench')
		OR users.user_key 
		IN ( SELECT coach_user_key FROM coach_teams WHERE teamID = '$teamID' AND season = '$coachmaxseason' )
		ORDER BY (m,d) < ( MONTH(CURDATE()), DAY(CURDATE()) )
       , m
       , d ASC LIMIT $amounttoshow";

	  	if ($db->query($sql)) {  
	    } else {
	      echo "Error: " . $sql . "<br>" . $db->error;
	    }

	  	$result = $db->query($sql);
	  
	  	echo '
		<div class="table-responsive">
		<table class="table table-striped">
		<thead>
		</thead>
		<tbody>';

	  	while ( $row = $result->fetch_assoc()) {

			$firstname = $row['firstname']; 
			$lastname = $row['lastname']; 
			$birthdate = $row['birthdate']; 

			$m = date('M', strtotime($birthdate));
			$d = date('d', strtotime($birthdate));
			$datethisyear = date('Y') . "-" . date('m', strtotime($birthdate)) . "-$d";
			$weekdaythisyear = date('D', strtotime($datethisyear));		

			$timestampconv = strtotime($birthdate);
			$date = date("dS M Y", $timestampconv);
			$datebirth = new DateTime($date);
			$datetoday = new DateTime("now");

			$mtoday = date('M');
			$dtoday = date('d');

			if ($m == $mtoday && $d == $dtoday ) {
				$interval = $datetoday->diff($datebirth);
		  		$age = $interval->y;
				echo "<tr> <td colspan='2' class='text-center'> <h4><strong> Today $firstname $lastname has become $age!</strong></h4> <td></tr>";
			} else {
				
				$interval = $datetoday->diff($datebirth);
		  		$age = $interval->y + 1;

		  		echo "<tr> 
		  		<td> $weekdaythisyear $d $m </td> 
		  		<td> $firstname $lastname </td> 
		  		<td> $age </td>
		  		</tr>";
			}

	  }

	  		echo '</tbody>
		</table>
		</div>';
	}

public function GetCurrentTeamIDFromPlayerKey($player_user_key)
	{
		require __DIR__ . '/db_bb_connect.php';

		$sql = "SELECT teamID
		FROM teams
		WHERE playerID = '$player_user_key'
		ORDER BY season DESC
		LIMIT 1";

		if ($db->query($sql)) {  
		} else {
			echo "Error: " . $sql . "<br>" . $db->error;
		}

		$result = $db->query($sql);
		$row = $result->fetch_assoc();
		$teamID = $row['teamID'];

		return $teamID;
	}

public function GetCurrentTeamIDFromCoachKey($coach_user_key)
	{

		require __DIR__ . '/db_bb_connect.php';

		$sql="SELECT teamID
		FROM coach_teams
		WHERE coach_user_key = '$coach_user_key'
		ORDER BY season DESC
		LIMIT 1";

		if ($db->query($sql)) {  
		} else {
			echo "Error: " . $sql . "<br>" . $db->error;
		}

		$result = $db->query($sql);
		$row = $result->fetch_assoc();
		$teamID = $row['teamID'];

		return $teamID;
	}

public function GetUpcomingGamesFromPlayerID($user_key, $amounttoshow)
	{
		$teamID = $this->GetCurrentTeamIDFromPlayerKey($user_key);
		$this->GetUpcomingGamesFromTeamID($teamID, $amounttoshow);
	}

public function GetUpcomingGamesFromCoachID($coach_user_key, $amounttoshow)
	{
		$teamID = $this->GetCurrentTeamIDFromCoachKey($coach_user_key);
		$this->GetUpcomingGamesFromTeamID($teamID, $amounttoshow);
	}

public function GetUpcomingGamesFromTeamID($teamID, $amounttoshow)
	{
		require __DIR__ . '/db_bb_connect.php';

		$sql = "SELECT *
		FROM games_list
		WHERE DATE(date) > DATE(NOW())
		AND (teamID_home = '$teamID'
		OR teamID_away = '$teamID')
		ORDER BY date ASC 
		LIMIT $amounttoshow";

		$result = $db->query($sql);	

		echo '
		<div class="table-responsive">
		<table class="table table-striped">
		<thead>
		</thead>
		<tbody>';

		

		while ( $row = $result->fetch_assoc()) {

			$gamedate = $row['date'];
			$gametype = $row['type'];
			$teamhomeID = $row['teamID_home'];
			$teamawayID = $row['teamID_away'];

			$gamedate_day = date('d',strtotime($gamedate));
			$gamedate_month = date('M',strtotime($gamedate));

			$sql2 = "SELECT teamname
			FROM teams_list
			WHERE teamID = '$teamhomeID'";
			
			$result2 = $db->query($sql2);
			$row2 = $result2->fetch_assoc();
			$hometeamname = $row2['teamname'];

			$sql2 = "SELECT teamname
			FROM teams_list
			WHERE teamID = '$teamawayID'";
			
			$result2 = $db->query($sql2);
			$row2 = $result2->fetch_assoc();
			$awayteamname = $row2['teamname'];

			if ($gametype == 'league') {
				$gametype = "L";
			} elseif($gametype == 'practice') {
				$gametype = "P";
			}
			echo "<tr>
			<td> $gamedate_day $gamedate_month </td> 
			<td> $hometeamname </td>
			<td> $awayteamname</td>
			</tr>";
		}
		echo '</tbody>
		</table>
		</div>';
	}

public function GetLastActiveSeasonFromPlayerID($playerID)
	{
		require __DIR__ . '/db_bb_connect.php';

		$sql = "SELECT season
		FROM teams
		WHERE playerID = '$playerID'
		ORDER BY season DESC
		LIMIT 1";

		if ($db->query($sql)) {  
		} else {
			echo "Error: " . $sql . "<br>" . $db->error;
		}

		$result = $db->query($sql);
		$row = $result->fetch_assoc();
		$season = $row['season'];

		return $season;
	}

public function GetLastActiveSeasonFromCoachID($coachID)
	{
		require __DIR__ . '/db_bb_connect.php';

		$sql="SELECT season
		FROM coach_teams
		WHERE coach_user_key = '$coachID'
		ORDER BY season DESC
		LIMIT 1";

		if ($db->query($sql)) {  
		} else {
			echo "Error: " . $sql . "<br>" . $db->error;
		}

		$result = $db->query($sql);
		$row = $result->fetch_assoc();
		$season = $row['season'];

		return $season;
	}

public function GetLastActiveTeamGoalsFilenameFromTeamID($teamID, $season)
	{
		//echo "<h4>Team goals of team $teamID season $season</h4>";
		require __DIR__ . '/db_bb_connect.php';

		$sql="SELECT filename
		FROM teamgoals
		WHERE teamID = '$teamID'
		AND season = '$season'";

		if ($db->query($sql)) {  
		} else {
			echo "Error: " . $sql . "<br>" . $db->error;
		}

		$result = $db->query($sql);

		$row = $result->fetch_assoc();
		$filename = $row['filename'];

		return $filename;		
	}

public function GetLastActiveTeamGoalsFilenameFromPlayerID($playerID)
	{
		$teamID = $this->GetCurrentTeamIDFromPlayerKey($playerID);
		$season = $this->GetLastActiveSeasonFromPlayerID($playerID);

		$filename = $this->GetLastActiveTeamGoalsFilenameFromTeamID($teamID, $season);

		return $filename;
	}

public function GetLastActiveTeamGoalsFilenameFromCoachID($coachID)
	{
		$teamID = $this->GetCurrentTeamIDFromCoachKey($coachID);
		$season = $this->GetLastActiveSeasonFromCoachID($coachID);

		$filename = $this->GetLastActiveTeamGoalsFilenameFromTeamID($teamID, $season);

		return $filename;
	}

public function GetTeamNameFromTeamID($teamID)
	{

		require __DIR__ . '/db_bb_connect.php';

		$sql="SELECT teamname
		FROM teams_list
		WHERE teamID = '$teamID'";

		if ($db->query($sql)) {  
		} else {
			echo "Error: " . $sql . "<br>" . $db->error;
		}

		$result = $db->query($sql);
		$row = $result->fetch_assoc();
		$teamname = $row['teamname'];

		return $teamname;
	}

public function GetTeamLeagueStandings($teamID, $season)
	{
		//get nbbleague ID
		require __DIR__ . '/db_bb_connect.php';

		$sql = "SELECT nbb_league_ID
		FROM nbb_api_ids
		WHERE teamID = '$teamID' AND season = '$season'";

		if ($db->query($sql)) {  
		} else {
			echo "Error: " . $sql . "<br>" . $db->error;
		}

		$result = $db->query($sql);
		$row = $result->fetch_assoc();
		$nbb_league_ID = $row['nbb_league_ID'];

		if($nbb_league_ID == '') {
			echo "No League ID in Database";
		} else {

		// print table

		include_once("./includes/nbbapi/class.nbb.php");
		include_once("./includes/nbbapi/class.stand.php");

		$stand = new Stand( $nbb_league_ID );

		list($nr, $naam) = $stand->competitie();
		$overzicht = $stand->overzicht();
		
		echo "<h4> League Standings $naam </h4>";
		echo "<div class=\"table-responsive\">";
					
		echo "<table class=\"table table-striped\">\n";
		echo "<thead>
		<td>#</td>
		<td>Team</td>
		<td>GP</td>
		<td>Pts.</td>
		<td>Saldo</td>
		</thead>
		<tbody>\n"; 

		foreach ($overzicht as $nr => $info) {
		   echo "<tr>
		   <td>$nr</td>
		   <td>" . $info['team'] . "</td>
		   <td>" . $info['gespeeld'] . "</td>
		   <td>" . $info['punten'] . "</td>   
		   <td>" . $info['saldo'] . "</td>
		   </tr>\n"; 
		}
		echo "</tbody></table> </div>\n";
		}
	}

public function GetTeamLeagueAllResults($teamID, $season)
	{	
		require __DIR__ . '/db_bb_connect.php';

		$sql = "SELECT nbb_league_ID
		FROM nbb_api_ids
		WHERE teamID = '$teamID' AND season = '$season'";

		if ($db->query($sql)) {  
		} else {
			echo "Error: " . $sql . "<br>" . $db->error;
		}

		$result = $db->query($sql);
		$row = $result->fetch_assoc();
		$nbb_league_ID = $row['nbb_league_ID'];

		if($nbb_league_ID == '') {
			echo "No League ID in Database";
		} else {

		include_once("./includes/nbbapi/class.nbb.php");
		include_once("./includes/nbbapi/class.competitie.php");
		include_once("./includes/nbbapi/class.wedstrijd.php");

		$org_ID = 1;  
		$wedstrijd = new Wedstrijd( $org_ID, $nbb_league_ID );
		list($nr, $naam) = $wedstrijd->competitie();
		echo "<div class=\"table-responsive\">";
		echo "<h4> Results $naam</h4>";
		print "<TABLE class=\"table table-striped\">\n";
		$overzicht = $wedstrijd->overzicht();
		$wedstrijd_lijst = $wedstrijd->wedstrijden($nbb_league_ID);

		function cmp($a, $b)
		{
		    $a_int = DateTime::createFromFormat('j-m-Y', $a["datum"])->getTimestamp();
		    $b_int = DateTime::createFromFormat('j-m-Y', $b["datum"])->getTimestamp();
		    return ($a_int == $b_int) ? 0 : ($a_int < $b_int) ? 1 : -1;
		}

		usort($wedstrijd_lijst, "cmp");

		foreach ($wedstrijd_lijst as $id => $details ) {
			if ( $details['scorethuis'] != 0 ){

			print "<TR>";
			print "<TD>" . $details['datum'] ."</TD>";
			print "<TD>" . $details['thuisclub'] . ' ' .$details['thuisteamafko'] ."</TD>";
			print "<TD>" . $details['uitclub'] . ' ' .$details['uitteamafko'] ."</TD>";
			print "<TD>" . $details['scorethuis'] . ' - ' . $details['scoreuit'] ."</TD>";

			print "</TR>\n";
			}
		}
		print "</TABLE> </div>\n\n";
		}
	}

public function GetUserLoginType()
	{	
		$sql = "SELECT type FROM users WHERE username = '$this->username'";
		$row = $this->FetchResults($sql);
		$type = $row['type'];
	 	return $type;
	}

public function GetTeamUserKeyFromTeamID($teamID)
	{
		$sql = "SELECT user_key FROM users WHERE user_key IN (SELECT playerID FROM teams JOIN users on teams.playerID = users.user_key WHERE teams.teamID = '$teamID' AND users.type = 'Team')";
		$row = $this->FetchResults($sql);
		$team_user_key = $row['user_key'];
		return $team_user_key;
	}

public function CheckIfPlayerInCoachteam($player_key, $coach_key)
	{
		$sql = "SELECT * FROM team_formations 
		JOIN coach_teams 
		ON team_formations.teamID = coach_teams.teamID 
		WHERE coach_teams.coach_user_key = '$coach_key' 
		AND team_formations.playerID = '$player_key'";

		$row = $this->FetchResults($sql);

		if (empty($row)) {
				return false;
			} else {
				return true;
			}				
	}

public function ShowTeamVisibleVideoFeedforwardCurrentTeam($feedback_type)
	{	
		require __DIR__ . '/db_bb_connect.php';

		$type = $this->GetUserLoginType();	

		if ( $type == "Coach" ){

			$coach_user_key = $this->GetUserkeyFromUsername($this->username);

			if ( isset($_POST['playerID']) ) {
				$player_user_key = $_POST['playerID'];
				$teamID = $this->GetCurrentTeamIDFromPlayerKey($player_user_key);
			} else {
				$teamID = $this->GetCurrentTeamIDFromCoachKey($coach_user_key);
			}	

		} elseif ( $type == "Player" ){
			$player_user_key = $this->GetUserkeyFromUsername($this->username);
			$teamID = $this->GetCurrentTeamIDFromPlayerKey($player_user_key);
		}

		$team_user_key = $this->GetTeamUserKeyFromTeamID($teamID);

		$videonr = 1;

		$sql = "SELECT video_ID FROM video_feedback_visibility WHERE user_key = '$team_user_key'";

		if ($db->query($sql)) {  
			$result = $db->query($sql);

			if ( mysqli_num_rows($result) == 0 ) {
				//echo "No videos to show";
			} else {

			while ($row = $result->fetch_assoc()) {
				$video_ID = $row['video_ID'];

				if ($feedback_type == "opponent") {
					$sql2 = "SELECT * FROM video_feedback WHERE ID = '$video_ID' AND action_tags LIKE '%32%'";
				} else {
					$sql2 = "SELECT * FROM video_feedback WHERE ID = '$video_ID' AND action_tags NOT LIKE '%32%'";
				}

				$result2 = $db->query($sql2);
				

				if ( mysqli_num_rows($result2) != 0 ) {
					
					$row2 = $result2->fetch_assoc();
					$season = $row2['season'];
					$gamenumber = $row2['gamenumber'];
					$title = $row2['title'];
					$comment = nl2br($row2['comment']);
					$time_start = $row2['time_start'];
					$time_end = $row2['time_end'];
					$duration = ($time_end - $time_start)*1000;

					$tags = str_replace(","," ", $row2['action_tags']);

					$embed_code = $this->GetGameEmbedCode($season, $gamenumber);
				
					echo "<div class=\"row\">
						<div class=\"col-md-12\"> <h4> Video $videonr: $title </h4></div>
						</div>
						<div class=\"row\">
						<div class=\"col-md-4\"> <div id=\"player$video_ID\"><button class=\"btn btn-sm btn-default loadvideo$video_ID clicklog\" name=\"video_feedback_team_$video_ID\">Load Video</button></div> </div>
						<div class=\"col-md-4\"> $comment </div>
						<div class=\"col-md-4\"> </div>
						</div> <hr>";


				?>

				<script type="text/javascript">
				var tag = document.createElement('script');

				tag.src = "https://www.youtube.com/iframe_api";
				var firstScriptTag = document.getElementsByTagName('script')[0];
				firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

				var player<?= $video_ID?>;
				var clicked<?= $video_ID?> = false;	

		       $(document).on("click",'.loadvideo<?= $video_ID?>', function(){

			       function onYouTubeIframeAPIReady() {
						player<?= $video_ID?> = new YT.Player('player<?= $video_ID?>', {
			          	height: '300',
			          	width: '100%',
			          	videoId: '<?= $embed_code?>',
			          	events: {
			            	'onStateChange': onPlayer<?= $video_ID?>StateChange
			          	}
				    });
		        	}

					onYouTubeIframeAPIReady(); 

			    }); 

	       		function onPlayer<?= $video_ID?>StateChange(e) { 
					if( !clicked<?= $video_ID?> ){	 
						clicked<?= $video_ID?> = true;
						player<?= $video_ID?>.seekTo(<?= $time_start?>); 
						loop<?= $video_ID?>Video();
					    e.preventDefault();
					};
				};


				function loop<?= $video_ID?>Video(){
					var timeout = <?= $duration?>;
					setTimeout(seek<?= $video_ID?>Video, timeout);          
				};

				function seek<?= $video_ID?>Video(){
					player<?= $video_ID?>.seekTo(<?= $time_start?>);
					loop<?= $video_ID?>Video();
				};
					


				</script>


				<?php	

				$videonr += 1;
				}
			} 
			}

			} else {
      		echo "Error: " . $sql . "<br>" . $db->error;
    		}  

    		////// End of Video Feedback Videos	/////

    		///// Other Videos /////

				$sql = "SELECT video_ID FROM video_other_visibility WHERE user_key = '$team_user_key'";

				if ($db->query($sql)) {  
					$result = $db->query($sql);

					if ( mysqli_num_rows($result) == 0 ) {
						//echo "No videos to show";
					} else {

					while ($row = $result->fetch_assoc()) {
						$video_ID = $row['video_ID'];

						$sql2 = "SELECT * FROM video_other WHERE ID = '$video_ID'";
						$result2 = $db->query($sql2);
						$row2 = $result2->fetch_assoc();

						$title = $row2['title'];
						$embed_code = $row2['embed_code'];
						$comment = nl2br($row2['comment']);

						echo "<div class=\"row\">
						<div class=\"col-md-12\"> <h4> Video $videonr: $title </h4></div>
						</div>
						<div class=\"row\">
						<div class=\"col-md-4\"> <div id=\"otherplayer$video_ID\"><button class=\"btn btn-sm btn-default loadothervideo$video_ID clicklog\" name=\"video_other_team_$video_ID\">Load Video</button></div> </div>
						<div class=\"col-md-4\"> $comment </div>
						<div class=\"col-md-4\"> </div>
						</div> <hr>";

						?>

				<script type="text/javascript">
				var tag = document.createElement('script');

				tag.src = "https://www.youtube.com/iframe_api";
				var firstScriptTag = document.getElementsByTagName('script')[0];
				firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

				var otherplayer<?= $video_ID?>;
				var otherclicked<?= $video_ID?> = false;	

		       $(document).on("click",'.loadothervideo<?= $video_ID?>', function(){

			       function onYouTubeIframeAPIReady() {
						otherplayer<?= $video_ID?> = new YT.Player('otherplayer<?= $video_ID?>', {
			          	height: '300',
			          	width: '100%',
			          	videoId: '<?= $embed_code?>'
				    });
		        	}

					onYouTubeIframeAPIReady(); 

			    }); 

				</script>

				<?php

					$videonr += 1;
					}
				}
			} else {
      		echo "Error: " . $sql . "<br>" . $db->error;
    		} 			
	}

public function ShowVisibleVideoFeedforwardPlayer()
	{	
		require __DIR__ . '/db_bb_connect.php';

		$type = $this->GetUserLoginType();	

		if ($type == "Coach"){

		$player_user_key = $_POST['playerID'];

		$teamID = $this->GetCurrentTeamIDFromPlayerKey($player_user_key);

		} elseif ($type == "Player"){

			$player_user_key = $this->GetUserkeyFromUsername($this->username);

			$teamID = $this->GetCurrentTeamIDFromPlayerKey($player_user_key);

		}

		$sql = "SELECT video_ID FROM video_feedback_visibility WHERE user_key = '$player_user_key'";

		?>	


		<?php

		$videonr = 1;

		if ($db->query($sql)) {  
			$result = $db->query($sql);

			if ( mysqli_num_rows($result) == 0 ) {
				echo "No videos to show";
			} else {
							

			while ($row = $result->fetch_assoc()) {
				$video_ID = $row['video_ID'];


				$sql2 = "SELECT * FROM video_feedback WHERE ID = '$video_ID'";
				$result2 = $db->query($sql2);
				$row2 = $result2->fetch_assoc();

				$season = $row2['season'];
				$gamenumber = $row2['gamenumber'];
				$title = $row2['title'];
				$comment = nl2br($row2['comment']);
				$time_start = $row2['time_start'];
				$time_end = $row2['time_end'];
				$duration = ($time_end - $time_start)*1000;

				$embed_code = $this->GetGameEmbedCode($season, $gamenumber);
			
				echo "<div class=\"row\">
					<div class=\"col-md-12\"> <h4> Video $videonr: $title </h4></div>
					</div>
					<div class=\"row\">
					<div class=\"col-md-4\"> <div id=\"player" . $video_ID . "Player\"><button class=\"btn btn-sm btn-default loadvideoPlayer$video_ID clicklog\" name=\"video_feedback_player_$video_ID\">Load Video</button></div> </div>
					<div class=\"col-md-4\"> $comment </div>
					<div class=\"col-md-4\"> </div>
					</div>";

				?>

				<script type="text/javascript">
				var tag = document.createElement('script');

				tag.src = "https://www.youtube.com/iframe_api";
				var firstScriptTag = document.getElementsByTagName('script')[0];
				firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

				var player<?= $video_ID?>Player;
				var clicked<?= $video_ID?>Player = false;	

		       $(document).on("click",'.loadvideoPlayer<?= $video_ID?>', function(){

			       function onYouTubeIframeAPIReady() {
						player<?= $video_ID?>Player = new YT.Player('player<?= $video_ID?>Player', {
			          	height: '300',
			          	width: '100%',
			          	videoId: '<?= $embed_code?>',
			          	events: {
			            	'onStateChange': onPlayer<?= $video_ID?>PlayerStateChange
			          	}
				    });
		        	}

					onYouTubeIframeAPIReady(); 

			    }); 

	       		function onPlayer<?= $video_ID?>PlayerStateChange(e) { 
					if( !clicked<?= $video_ID?>Player ){	 
						clicked<?= $video_ID?>Player = true;
						player<?= $video_ID?>Player.seekTo(<?= $time_start?>); 
						loop<?= $video_ID?>PlayerVideo();
					    e.preventDefault();
					};
				};


				function loop<?= $video_ID?>PlayerVideo(){
					var timeout = <?= $duration?>;
					setTimeout(seek<?= $video_ID?>PlayerVideo, timeout);          
				};

				function seek<?= $video_ID?>PlayerVideo(){
					player<?= $video_ID?>Player.seekTo(<?= $time_start?>);
					loop<?= $video_ID?>PlayerVideo();
				};

				</script>

				<?php	

				$videonr += 1;
				}
			} 

		} else {
      		echo "Error: " . $sql . "<br>" . $db->error;
    	}  

    		////// End of Video Feedback Videos	/////

    		///// Other Videos /////

				$sql = "SELECT video_ID FROM video_other_visibility WHERE user_key = '$player_user_key'";

				if ($db->query($sql)) {  
					$result = $db->query($sql);

					if ( mysqli_num_rows($result) == 0 ) {
						//echo "No videos to show";
					} else {

					while ($row = $result->fetch_assoc()) {
						$video_ID = $row['video_ID'];

						$sql2 = "SELECT * FROM video_other WHERE ID = '$video_ID'";
						$result2 = $db->query($sql2);
						$row2 = $result2->fetch_assoc();

						$title = $row2['title'];
						$embed_code = $row2['embed_code'];
						$comment = nl2br($row2['comment']);

						echo "<div class=\"row\">
						<div class=\"col-md-12\"> <h4> Video $videonr: $title </h4></div>
						</div>
						<div class=\"row\">
						<div class=\"col-md-4\"> <div id=\"otherplayer".$video_ID ."Player\"><button class=\"btn btn-sm btn-default loadothervideoPlayer$video_ID \" name=\"video_other_player_$video_ID\">Load Video</button></div> </div>
						<div class=\"col-md-4\"> $comment </div>
						<div class=\"col-md-4\"> </div>
						</div> <hr>";

						?>

				<script type="text/javascript">
				var tag = document.createElement('script');

				tag.src = "https://www.youtube.com/iframe_api";
				var firstScriptTag = document.getElementsByTagName('script')[0];
				firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

				var otherplayer<?= $video_ID?>Player;
				var otherclicked<?= $video_ID?>Player = false;	

		       $(document).on("click",'.loadothervideoPlayer<?= $video_ID?>', function(){

			       function onYouTubeIframeAPIReady() {
						otherplayer<?= $video_ID?>Player = new YT.Player('otherplayer<?= $video_ID?>Player', {
			          	height: '300',
			          	width: '100%',
			          	videoId: '<?= $embed_code?>'
				    });
		        	}

					onYouTubeIframeAPIReady(); 

			    }); 

				</script>

				<?php

					$videonr += 1;
					}
				}
			} else {
      		echo "Error: " . $sql . "<br>" . $db->error;
    		} 

	}

}

?>